<template>
  <transition name="fade-slide">
    <div v-if="showConsent" class="cookie-consent">
      <div class="cookie-consent-content">
        <div class="cookie-consent-message">
          <h3>{{ $t('common.cookieConsent.title') }}</h3>
          <p>{{ $t('common.cookieConsent.message') }}</p>
        </div>
        <div class="cookie-consent-buttons">
          <a-button type="primary" size="small" @click="rejectCookies">
            {{ $t('common.cookieConsent.reject') }}
          </a-button>
          <a-button size="small" @click="acceptCookies">
            {{ $t('common.cookieConsent.accept') }}
          </a-button>
        </div>
      </div>
    </div>
  </transition>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import {
  getCookieConsentStatus,
  setCookieConsentStatus,
  hasAcceptedCookies
} from '@/utils/cache';

// 控制是否显示同意提示框
const showConsent = ref(false);

/**
 * 接受 Cookie 使用
 */
const acceptCookies = () => {
  setCookieConsentStatus(true);
  hideConsentWithAnimation();
};

/**
 * 拒绝 Cookie 使用
 */
const rejectCookies = () => {
  setCookieConsentStatus(false);
  hideConsentWithAnimation();
};

/**
 * 带动画效果隐藏同意提示
 */
const hideConsentWithAnimation = () => {
  // 先添加隐藏动画类
  const consentEl = document.querySelector('.cookie-consent');
  if (consentEl) {
    consentEl.classList.add('hide');

    // 动画结束后再实际隐藏组件
    setTimeout(() => {
      showConsent.value = false;
    }, 500); // 动画持续时间
  } else {
    // 如果找不到元素，直接隐藏
    showConsent.value = false;
  }
};

/**
 * 检查是否需要显示 Cookie 同意提示
 */
const checkCookieConsent = () => {
  // 如果用户已经接受使用 Cookie，则不显示提示
  if (hasAcceptedCookies()) {
    showConsent.value = false;
  } else {
    // 否则，显示提示
    showConsent.value = true;
  }
};

// 组件挂载时检查 Cookie 同意状态
onMounted(() => {
  // 使用 setTimeout 确保在页面渲染后显示提示
  setTimeout(() => {
    checkCookieConsent();
  }, 1000);
});
</script>

<style scoped lang="scss">
.cookie-consent {
  position: fixed;
  left: 20px;
  bottom: 20px;
  z-index: 9999;
  width: 320px;
  max-width: calc(100% - 40px);
  transition: all 0.5s ease;

  &.hide {
    transform: translateY(100%);
    opacity: 0;
  }
}

.cookie-consent-content {
  background-color: #000000;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 16px;
  border: 1px solid #000000;
}

.cookie-consent-message {
  margin-bottom: 16px;

  h3 {
    font-size: 16px;
    margin: 0 0 8px 0;
    color: #FFFFFF;
  }

  p {
    font-size: 14px;
    color: #FFFFFF;
    margin: 0;
    line-height: 1.5;
  }
}

.cookie-consent-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

// 进入和离开的过渡动画
.fade-slide-enter-active {
  transition: all 0.5s ease-out;
}

.fade-slide-leave-active {
  transition: all 0.5s ease-in;
}

.fade-slide-enter-from,
.fade-slide-leave-to {
  transform: translateY(100%);
  opacity: 0;
}

@media (max-width: 576px) {
  .cookie-consent {
    left: 10px;
    bottom: 10px;
    width: calc(100% - 20px);
  }
}
</style>
